﻿using System.IO;
using System.Net;

namespace SimpleNoteLib.HttpRequests
{
    internal class HttpPostRequest : IHttpRequest
    {
        public string Address { get; set; }
        public IWebProxy Proxy { get; set; }
        public byte[] Data { get; set; }

        public HttpPostRequest()
        {
            Address = Config.SimpleNoteApiConfig.LoginApiAddress;
            Proxy = Config.SimpleNoteApiConfig.Proxy;
        }

        public HttpPostRequest(string address, IWebProxy proxy = null)
        {
            Address = address;
            Proxy = proxy;
        }

        public HttpPostRequest(string address, byte[] data, IWebProxy proxy = null)
        {
            Address = address;
            Data = data;
            Proxy = proxy;
        }

        public virtual string SendAndGetResponse()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Address);

            request.Proxy = Proxy;

            request.Method = "POST";
            request.ContentType = "application/json";
            request.ContentLength = Data.Length;
            request.UserAgent = "MyApp/0.5.0";
            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(Data, 0, Data.Length);
                stream.Close();
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string result = new StreamReader(response.GetResponseStream()).ReadToEnd();
            return result;
        }
    }
}
